/*
 *  PPURLConnection.m
 *  PigeonsFoundation
 *
 *  Created by Jacob Basham on 1/16/07.
 *  Copyright 2007, PaperPigeons.net
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without 
 *  modification, are permitted provided that the following conditions 
 *  are met:
 *  1. Redistributions of source code must retain the above copyright 
 *     notice, this list of conditions and the following disclaimer.
 *	2. Redistributions in binary form must reproduce the above copyright 
 *	   notice, this list of conditions and the following disclaimer in 
 *	   the documentation and/or other materials provided with the distribution.
 *	3. Neither the name of PaperPigeons.net nor the names of its contributors 
 *	   may be used to endorse or promote products derived from this software 
 *	   without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 *	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 *	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
 *	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
 *	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
 *	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 *	BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 *	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
 *	CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
 *	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
 *	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 *	POSSIBILITY OF SUCH DAMAGE.
 */

#import "PPURLConnection.h"


@implementation PPURLConnection

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request
	authenticator:(id)authenticator 
	returningResponse:(NSHTTPURLResponse **)response
	error:(NSError **)error
{
	// init connection object and load request
	id connection = [[self alloc] initWithAuthenticator:authenticator];
	[connection loadURLRequest:request];
	
	// return results
	*error = (NSError *)[connection error];
	*response = (NSHTTPURLResponse *)[connection response];
	return [connection data];
}

- (id)initWithAuthenticator:(id)authenticator
{
	if (self = [super init]) {
		// init run loop settings
		_run = YES;
		_runLoop = [NSRunLoop currentRunLoop];
		_authenticator = authenticator;
	}
	return self;	
}

- (void)loadURLRequest:(NSURLRequest *)request
{
	SEL selector = @selector(authenticateRequest:);
	
	// send request to authenticator delegate
	if ([_authenticator respondsToSelector:selector]) {
		objc_msgSend(_authenticator, selector, &request);
	}
	
	// init connection
	NSURLConnection * connection = [[NSURLConnection alloc]
		initWithRequest:_request delegate:self];
	
	if (!connection) {
		return;
	}
	
	// init mutable data container
	_data = [[NSMutableData data] retain];
	
	// wait for data or error
	while (_run && [_runLoop runMode:NSDefaultRunLoopMode 
		beforeDate:[NSDate distantFuture]]);
}

- (NSData *)data 
{ 
	return [NSData dataWithData:_data]; 
}

- (NSError *)error 
{ 
	return _error; 
}

- (NSHTTPURLResponse *)response 
{ 
	return _response; 
}

- (void)connection:(NSURLConnection *)connection
	didReceiveResponse:(NSHTTPURLResponse *)response
{
	// store response
	_response = response;
	
	// reset data
	[_data setLength:0];
}
	
- (NSURLRequest *)connection:(NSURLConnection *)connection
	willSendRequest:(NSURLRequest *)request
	redirectResponse:(NSHTTPURLResponse *)redirectResponse
{
	// copy orig request settings to redirect request
	NSMutableURLRequest * newRequest = [request mutableCopy];
	NSDictionary * headers = [_request allHTTPHeaderFields];
	
	[newRequest setHTTPBody:[_request HTTPBody]];
	[newRequest setHTTPMethod:[_request HTTPMethod]];
	
	// TODO should all headers be copied?
	[newRequest setValue:[headers valueForKey:@"Content-Type"] 
		forHTTPHeaderField:@"Content-Type"];
	[newRequest setValue:[headers valueForKey:@"Authorization"] 
		forHTTPHeaderField:@"Authorization"];


	return newRequest;
}

- (void)connection:(NSURLConnection *)connection
	didReceiveData:(NSData *)data
{
	// append received bytes
	[_data appendData:data];
}

- (void)connection:(NSURLConnection *)connection
	didFailWithError:(NSError *)error
{
	// store error message
	_error = error;
	
	// stop run loop
	_run = NO;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// stop run loop
	_run = NO;
}

- (void)dealloc
{
	[_data release];
	[super dealloc];
}

@end
